/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fasea.ui.search;

import fasea.constants.Constants;
import fasea.model.Action;
import fasea.search.SearchResults;
import fasea.ui.AbstractController;
import fasea.ui.utils.InputDelayer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Date;

/**
 *
 * @author lars-wolfram
 */
public class SearchController extends AbstractController<SearchView> {
    
    
    
    private InputDelayer delayer = new InputDelayer(500) {

        @Override
        public void doSomething() {
            performSearch(view.getSearchText());
        }
    };

    private void performSearch(String userInput) {
        model.performSearch(userInput);
    }
    
    private void view() {
        if (model.getLastIndexed() == 0 || new Date().getTime() - model.getLastIndexed() > Constants.getIndexExpirationTime()) {
            view.setIndexAlertIcon();
        }
        else {
            view.setIndexOKIcon();
        }
        view.setVisible(true);
    }

    @Override
    public void update(Action action) {
        switch(action){
            case SEARCH_FINISHED:
                SearchResults results = model.getSearchResults();
                view.printResults(results);
                break;
            case INDEXER_ABORTED:
                view.setIndexAlertIcon();
                break;
            case INDEXER_FINISHED:
                 view.setIndexOKIcon();
                break;
            case INDEXER_STARTED:
                view.setIndexRunningIcon();
                break;
           case SHOW_SEARCHVIEW:
                view();
                break;
        }
    }

    @Override
    protected void initView(){
        this.view.addPropertiesButtonActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                model.showPropertiesViewButtonClicked();
            }
        });
       this.view.addSearchFieldKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(java.awt.event.KeyEvent evt) {
                if (evt.getKeyCode() != KeyEvent.VK_ESCAPE && evt.getKeyCode() != KeyEvent.VK_ENTER && evt.getKeyCode() != KeyEvent.VK_DOWN && evt.getKeyCode() != KeyEvent.VK_UP) {
                    delayer.run();
                }else if(evt.getKeyCode() == KeyEvent.VK_ENTER){
                    model.openFileInSearchResult(view.getSelectedResultIndex());
                }else if(evt.getKeyCode() == KeyEvent.VK_UP){
                    view.selectPreviousEntry();
                }else if(evt.getKeyCode() == KeyEvent.VK_DOWN){
                    view.selectNextEntry();
                }
            }
        });
    }
}
